<?php

namespace app\api\controller;

use app\common\Helper;
use app\common\model\Specialofferrule;
use app\common\model\Userreceivetic;
use app\common\model\Storecancelrecord;
use app\api\service\Pay;
use app\common\validate\requestPaymentValidate;
use app\lib\exception\ParameterException;
use think\Db;
use think\Request;

class Ticket extends Base
{

    // 创建优惠券
    public function createTicket(Request $request){
        if($request->isPost()){
            $param = $request->param();
            Db::startTrans();
            try{
                if(!$this->checkparam($param)){
                    return show(config('status.error_code'),'参数不合法','参数不合法');
                }
                $SpecialofferruleModel = new Specialofferrule();
                $SpecialofferruleId = Helper::getUUID();
                $SpecialofferruleModel->id = $SpecialofferruleId;
                $specialofferrule = $param['ticket']['specialofferrule'];
                $this->getspecialofferrule($specialofferrule,$SpecialofferruleModel);
                $SpecialofferruleModel->save();

                $TicketModel = new \app\admin\model\Ticket();
                $endtime = $param['ticket']['endTime'] . ' 23:59:59';
                $ticketId = Helper::getUUID();
                $TicketModel->id = $ticketId;
                $TicketModel->name = $specialofferrule['specialOfferName'];
                $TicketModel->specialOfferId = $SpecialofferruleId;
                $TicketModel->storeId = $param['storeId'];
                $TicketModel->beginTime = $param['ticket']['beginTime'];
                $TicketModel->endTime = $endtime;
                if($TicketModel->endTime <= date('Y-m-d',time())){
                    $TicketModel->status = 2;
                }else{
                    $TicketModel->status = 5;
                }
                $TicketModel->getGross = $param['ticket']['getGross'];
                $TicketModel->limitGross = $param['ticket']['limitGross'];
                $TicketModel->getMethod = $param['ticket']['getMethod'];
                $TicketModel->buyTicketMoney = isset($param['ticket']['buyTicketMoney'])?$param['ticket']['buyTicketMoney']:NULL;
                $TicketModel->specialOfferStatement = $param['ticket']['specialOfferStatement'];
                $TicketModel->remainGross = $param['ticket']['getGross'];
                $TicketModel->save();

                Db::commit();
                return show(config('status.success_code'),'创建优惠券成功','创建优惠券成功');
            }catch (Exception $ex){
                Db::rollback();
                return show(config('status.error_code'),'创建优惠券失败','创建优惠券失败');
            }
        }else{
            return show(config('status.error_code'),'非法请求','非法请求');
        }
    }

    private function getspecialofferrule($specialofferrule,$SpecialofferruleModel){
        if(isset($specialofferrule['deductionMoney']) && !empty($specialofferrule['deductionMoney'])){
            $SpecialofferruleModel->deductionMoney = $specialofferrule['deductionMoney'];
        }elseif (isset($specialofferrule['commodityForFree']) && !empty($specialofferrule['commodityForFree'])){
            $SpecialofferruleModel->commodityForFree = $specialofferrule['commodityForFree'];
        }elseif (isset($specialofferrule['chargeMoney']) && !empty($specialofferrule['chargeMoney'])){
            $SpecialofferruleModel->chargeMoney = $specialofferrule['chargeMoney'];
            $SpecialofferruleModel->commodityForCharge = $specialofferrule['commodityForCharge'];
        }elseif (isset($specialofferrule['consumeMoney']) && !empty($specialofferrule['consumeMoney'])){
            $SpecialofferruleModel->consumeMoney = $specialofferrule['consumeMoney'];
            $SpecialofferruleModel->reduceMoney = $specialofferrule['reduceMoney'];
        }elseif (isset($specialofferrule['discountForAll']) && !empty($specialofferrule['discountForAll'])){
            $SpecialofferruleModel->discountForAll = $specialofferrule['discountForAll'];
        }
        $SpecialofferruleModel->specialOfferName = $specialofferrule['specialOfferName'];
    }

    private function checkparam($param){
        $Store = \app\admin\model\Store::get($param['storeId']);
        if($Store){
            if(!isset($param['ticket']['specialofferrule']['specialOfferName'])){
                return false;
            }
            if(empty($param['ticket']['getGross'])){
                return false;
            }
            if(empty($param['ticket']['beginTime']) || empty($param['ticket']['endTime'])){
                return false;
            }
        }else{
            return false;
        }

        return true;
    }

    //优惠券详情
    public function getTicketDetails(Request $request){
        $param = $request->param();
        if(empty($param['ticketId'])){
            return show(config('status.error_code'),'缺少参数','缺少参数');
        }
        $data = [];
        $Ticket = \app\admin\model\Ticket::get($param['ticketId']);
        if($Ticket && ($Ticket->status==5 || $Ticket->status==4 || $Ticket->status==2)){
            $Store = \app\admin\model\Store::get($Ticket->storeId);
            if($Store){
                $data['ticket'] = $Ticket;
                $data['store'] = $Store;
                return show(config('status.success_code'),'ok',$data);
            }else{
                return show(config('status.error_code'),'店铺不存在','店铺不存在');
            }
        }else{
            return show(config('status.error_code'),'此优惠活动不存在','此优惠活动不存在');
        }
    }

    /**
     * 删除优惠
     */
    public function deleteTicket(Request $request){
        $param = self::getHttpParam();

        if (empty($param->ticketId)) {
            return show(config('status.error_code'), self::NOT_PARAM, 'ticketId 不能为空');
        }

        $model = new \app\admin\model\Ticket();
        $ticket = $model->get($param->ticketId);
        if(!$ticket){
            return show(config('status.error_code'), '该券不存在', '该券不存在');
        }
        $userreceivetic = Userreceivetic::where(['ticketId' => $ticket->id, 'status' => 0])->find();
        if($userreceivetic){
            return show(config('status.error_code'),'已有人领取该券,不能删除','已有人领取该券,不能删除');
        }
        $ticket->status = 3;
        $result = $ticket->save();

        if($result === false){
            return show(config('status.error_code'), '删除失败', '删除失败');
        }

        return show(config('status.success_code'), '删除成功', '删除成功');
    }

    //免费领取优惠券
    public function receiveTicket(Request $request){
        $param = $request->param();
        if(empty($param['ticketId']) || empty($param['storeId'])){
            return show(config('status.error_code'),'参数错误','参数错误');
        }
        //判断店铺的状态
        $Store = \app\admin\model\Store::get($param['storeId']);
        if($Store->status != 1){
            return show(config('status.error_code'),'店铺已经关闭','店铺已经关闭');
        }
        try{
            $check = $this->checkticket($param);
            if(!$check['pass']){
                if($check['status'] == 1000){
                    return show(config('status.error_code'),'此优惠券已过期','此优惠券已过期');
                }elseif ($check['status'] == 2000){
                    return show(config('status.error_code'),'您的限领次数已经用完，不能再领取','您的限领次数已经用完，不能再领取');
                }else{
                    return show(config('status.error_code'),'此优惠券售罄','此优惠券售罄');
                }
            }
            $UserreceiveticModel = new Userreceivetic();
            $UserreceiveticModel->id = Helper::getUUID();
            $UserreceiveticModel->userId = $param['userId'];
            $UserreceiveticModel->storeId = $param['storeId'];
            $UserreceiveticModel->ticketId = $param['ticketId'];
            $UserreceiveticModel->receiveTicketTime = date('Y-m-d H:i:s',time());
            $UserreceiveticModel->save();
            $Ticket = \app\admin\model\Ticket::get($param['ticketId']);
            $Ticket->setDec('remainGross',1);
            Db::commit();
            return show(config('status.success_code'),'领取成功','领取成功');
        }catch (Exception $ex){
            Db::rollback();
            return show(config('status.error_code'),'领取失败','领取失败');
        }
    }

    public function checkticket($param){
        $pass = [
            'status' => 1,
            'pass' => true
        ];
        $Ticket = \app\admin\model\Ticket::where(['id'=>$param['ticketId'],'status'=>5])->where('status',['=', 5], ['=', 4], ['=', 2],'or')->find();
        if(!$Ticket){
            throw new ParameterException([
                'msg' => '该活动不存在'
            ]);
        }else{
            if($Ticket->remainGross < 1){
                $pass['status'] = 3000;
                $pass['pass'] = false;
            }
        }

        if(date('Y-m-d H:i:s',time())>$Ticket->endTime){
            $pass['status'] = 1000;
            $pass['pass'] = false;
        }
        $Ticket = \app\admin\model\Ticket::get($param['ticketId']);
        $Userreceivetic = Userreceivetic::where(['userId'=>$param['userId'],'ticketId'=>$param['ticketId']])->select();
        $count = count($Userreceivetic);
        if($Ticket->limitGross<=$count){
            $pass['status'] = 2000;
            $pass['pass'] = false;
        }
        return $pass;
    }

    // 核销记录
    public function getCancelRecord(Request $request){
        $param = $request->param();

        $start = 0;
        $length = 20;
        if(empty($param['storeId'])){
            return show(config('status.error_code'), self::NOT_PARAM, 'storeId 不能为空');
        }
        if (!empty($param['start'])) {
            $start = $param['start'];
        }
        if (!empty($param['length'])) {
            $length = $param['length'];
        }

        $where = [
            'storeId' => $param['storeId'],
            'status' => 1
        ];
        $result = Userreceivetic::where($where)->order('useTime Desc')->limit($start,$length)->select();
        $total = Userreceivetic::where($where)->count();

        if (empty($result)) {
            return show(config('status.error_code'), self::NOT_DATA, '未查到核销记录');
        }

        foreach ($result as &$item){
            $storeInfo = \app\admin\model\Store::get($item['storeId']);
            $item['store'] = $storeInfo;
            $ticketInfo = \app\admin\model\Ticket::get($item['ticketId']);
            $item['ticket'] = $ticketInfo;
            $userInfo = \app\admin\model\User::get($item['userId']);
            $item['user'] = $userInfo;
        }

        return showTotal(config('status.success_code'), self::MSG_SUCCESS, $result, $total);
    }

    // 删除核销记录
    public function deleteCancelRecord(Request $request){
        $param = $request->param();

        if(empty($param['id'])){
            return show(config('status.error_code'), self::NOT_PARAM, 'id 不能为空');
        }

        $where = [
            'id' => $param['id']
        ];
        $result = Storecancelrecord::where($where)->update(['status' => 2]);

        if($result === false){
            return show(config('status.error_code'), '删除失败', '删除失败');
        }

        return show(config('status.success_code'), '删除成功', '删除成功');
    }

    //支付时获取可用的优惠券
    public function getTicketForPay(Request $request){
        $param = $request->param();
        if(empty($param['payMoney']) || empty($param['storeId']) || empty($param['userId'])){
            return show(config('status.error_code'),'缺少参数','缺少参数');
        }
        $where = [
            'a.storeId' => $param['storeId'],
            'a.userId' => $param['userId'],
            'a.status' => 0
        ];
        $join = [
            ['__TICKET__ t','t.id=a.ticketId']
        ];
        $field = 't.*,a.id as receiveticId,a.userId,a.ticketId,a.status as status,a.receiveTicketTime';
        $Ticket = model('userreceivetic')->alias('a')->where($where)->join($join)->field($field)->select();
        if($Ticket){
            $count = count($Ticket);
            for($i=0;$i<$count;$i++){
                $Specialofferrule = Specialofferrule::get($Ticket[$i]['specialOfferId']);
                if($Specialofferrule){
                    if(($Specialofferrule->reduceMoney && $param['payMoney']>=$Specialofferrule->consumeMoney) ||
                        ($Specialofferrule->deductionMoney && $param['payMoney']>$Specialofferrule->deductionMoney) ||
                        $Specialofferrule->discountForAll ||
                        ($Specialofferrule->chargeMoney && $param['payMoney']>=$Specialofferrule->chargeMoney)){

                        $Ticket[$i]['specialOfferRule'] = $Specialofferrule;
                    }else{
                        unset($Ticket[$i]);
                    }
                }else{
                    continue;
                }
            }
            $Ticket = array_values($Ticket);
            return show(1,'ok',$Ticket);
        }else{
            return show(2,'暂无可用优惠券',null);
        }
    }

    //优惠券扫码核销

    public function insertCancelRecord(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['receiveticId']) || empty($param['ticketId']) || empty($param['storeId']) || empty($param['userId'])){
                return show(config('status.error_code'),'缺少参数','缺少参数');
            }
            $Userreceivetic = Userreceivetic::get($param['receiveticId']);
            if($Userreceivetic){
                if($Userreceivetic->storeId == $param['storeId']){
                    if($Userreceivetic->userId==$param['userId'] && $Userreceivetic->ticketId == $param['ticketId']){
                        if($Userreceivetic->status == 0){
                            $Ticket = \app\admin\model\Ticket::get($param['ticketId']);
                            $nowtime = date('Y-m-d H:i:s');
                            if($nowtime >= $Ticket->beginTime && $nowtime <= $Ticket->endTime){
                                $Userreceivetic->status = 1;
                                $Userreceivetic->useTime = date('Y-m-d H:i;s',time());
                                $Userreceivetic->save();
                                return show(config('status.success_code'),'核销成功','核销成功');
                            }else{
                                if($nowtime<$Ticket->beginTime){
                                    return show(config('status.error_code'),'优惠活动还没开始','优惠活动还没开始');
                                }
                                if($nowtime>$Ticket->endTime){
                                    return show(config('status.error_code'),'优惠券已经过期','优惠券已经过期');
                                }
                            }
                        }else{
                            return show(config('status.error_code'),'优惠券已经使用过','优惠券已经使用过');
                        }
                    }else{
                        return show(config('status.error_code'),'用户信息异常','用户信息异常');
                    }
                }else{
                    return show(config('status.error_code'),'店铺不匹配','店铺不匹配');
                }

            }else{
                return show(config('status.error_code'),'优惠券不存在','优惠券不存在');
            }
        }else{
            return show(config('status.error_code'),'非法请求','非法请求');
        }


    }

    //微信支付结果回调地址
    public function receiveNotify(){
        //通知频率为15/15/30/180/1800/1800/1800/1800/3600，单位：秒
        //1.检测库存量
        //2.更新订单状态
        //3.减库存
        //如果成功处理，则向微信返回成功处理的消息

        //特点：post；xml格式；不会携带参数

        $notify = new \app\api\service\WxNotify();
        $notify->Handle();

    }

}